package data.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DataConnector {
	private DataProperties dataProperties;
	private Connection connection = null;
	private String databaseType;
	
	public DataConnector() {
		super();
		this.dataProperties = new DataProperties();
		this.databaseType = dataProperties.getType();
	}
	
	private boolean testDriver() {
		boolean result = false;
		try {
			Class.forName(dataProperties.getDriver());
			result = true;
		} catch (ClassNotFoundException ex) {
			String errorString = dataProperties.getType() + " JDBC Driver not found...";
			System.err.println(errorString);
		}
		return result;
	}
	
	public Connection getConnection() {
		if(testDriver()) {
			if(DataProperties.MS_SQL_SERVER.equalsIgnoreCase(databaseType)) {
				String url = "jdbc:sqlserver://" +
							dataProperties.getServer() + 
							":" +
							dataProperties.getPort() +
							";" +
							"databaseName =" +
							dataProperties.getDatabaseName() +
							";selectMethod=cursor"; 
				try {
					this.connection = DriverManager.getConnection(url, dataProperties.getUserName(), dataProperties.getPassword());
				} catch (SQLException e) {
					e.printStackTrace();
				}
			} else if (DataProperties.MYSQL_SERVER.equalsIgnoreCase(databaseType)) {
				String url = "jdbc:mysql://" +
							dataProperties.getServer() + 
							":" +
							dataProperties.getPort() +
							"/" +
							dataProperties.getDatabaseName();
				try {
					this.connection = DriverManager.getConnection(url, dataProperties.getUserName(), dataProperties.getPassword());
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return this.connection;
	}
}
